/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import util.Data_variante;
import util.Lucene_Index;
import util.user_info;

/**
 *
 * @author dragonboy
 */


public class add_remove_user extends HttpServlet {
    String [] User_Type= {"","Member","Admin","SuperAdmin"};
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    protected void show_user_info2(PrintWriter out, int currUserType , String currUserName) throws CorruptIndexException, IOException, ParseException{
        File file = new File(Data_variante.loginDB_file);
        FSDirectory dir = FSDirectory.open(file);
        Searcher searcher
            = new IndexSearcher(dir);
        QueryParser parser = new QueryParser(Version.LUCENE_34, "UserID", new StandardAnalyzer(Version.LUCENE_34));
        //String command = "Username:"+username+" AND Status:"+passwd;
        String command = "Username:" + currUserName + "OR Boss:" + currUserName;
        Query myquery = parser.parse(command);
        TopDocs results = searcher.search(myquery,50);
        ScoreDoc[] hits = results.scoreDocs;
        int numUser = 0;
        for(ScoreDoc hit: hits){
            Document d = searcher.doc(hit.doc);
            numUser++;
            out.println("<tr>"
                        +"<td class=\"table-the-first\">"+ numUser +"</td>"
                        +"<td>"+ d.get("Username") +"</td>"
                        +"<td class=\"content-action-table-comment\">"+ d.get("Displayname") +"</td>"
                        +"<td>"+ User_Type[Integer.valueOf(d.get("Type"))] +"</td>"
                        +"<td>"+ d.get("LastLogin") +"</td>"
                        +"</tr>");
        }
    }
    
    protected boolean checkUsername1(PrintWriter out,File fFile, String username, String passwd, String displayName, int typeUser, String mode, String bossOfUser) throws IOException, ParseException{
        boolean _result = false;
        File file = new File(Data_variante.loginDB_file);
        FSDirectory dir = FSDirectory.open(file);
        Searcher searcher
            = new IndexSearcher(dir);
        QueryParser parser = new QueryParser(Version.LUCENE_34, "UserID", new StandardAnalyzer(Version.LUCENE_34));
        String command = "Username:"+username+" AND Status:"+passwd;
        Query myquery = parser.parse(command);
        TopDocs results = searcher.search(myquery,10);
        int total = results.totalHits;
        ScoreDoc[] hits = results.scoreDocs;
        if(mode.equals("Add")){
            if(total == 1){
                _result = false;
            }else{
                //add new Doc
                Document doc = new Document();
                doc.add(new Field("UserID", "1", Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Username", username ,Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Passwd", passwd, Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Displayname", displayName, Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Type", String.valueOf(typeUser), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("LastLogin", "null", Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Boss", bossOfUser, Field.Store.YES, Field.Index.ANALYZED));
                searcher.close();
                IndexWriter writer = new IndexWriter(dir, Lucene_Index.getAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
                writer.addDocument(doc);
                writer.close();
                _result = true;
            }
        }else if(mode.equals("remove")){
            if(total == 0){
                _result = false;
            }else{
                //remove Doc
                int docid = hits[0].doc;
                IndexReader reader = IndexReader.open(dir, false);
                reader.deleteDocument(docid);
                reader.close();
                _result = true;
            }
        }
        return _result;
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, CorruptIndexException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        File loginDb = new File("/data/contentfiltering/loginDB.txt");
        
        HttpSession session = request.getSession(false);
        if (session == null){
            response.sendRedirect("../index.html");
            return;
        }
        int currUserType = Integer.valueOf((String) session.getAttribute("userType"));
        String currUserName = (String)session.getAttribute("username");
        String bossOfUser = (String)session.getAttribute("bossOfUser");
        String bossOfNewUser;
        if(!bossOfUser.equals("null")){
            bossOfNewUser = bossOfUser + "-"+ currUserName;
        }else{
            bossOfNewUser = currUserName;
        }
            
        String type_user = request.getParameter("user_type");
        int typeUser;
        for(typeUser = 0; typeUser < User_Type.length; typeUser++ ){
            if (User_Type[typeUser].equals(type_user)){
                break;
            }
        }
        String user_name = request.getParameter("username");
        String passwd = request.getParameter("password");
        String re_passwd = request.getParameter("retypepassword");
        String disp_name = (request.getParameter("displayname") != null) ? request.getParameter("displayname"): request.getParameter("username");  
        disp_name = disp_name.replaceAll("%20", " ");
        String pressed_button = request.getParameter("add_remove");
        System.out.println("pressed_button: "+ pressed_button);
        String query = request.getQueryString();
        System.out.println("Infor: "+ user_name +"  "+ passwd +"  "+ re_passwd +"  "+ disp_name);
        
        if(pressed_button.equals("Add")){
            if(user_name.equals("") || passwd.equals("") || !passwd.equals(re_passwd)){
                //to do show invalid add action
                out.println("<div><b>Invalid Add action</b>: User name,passwd must not blank, retype passwd must match with passwd!!!</div>");
            }
            else{
                //check and add user checkUsername(loginDb, user_name, passwd, "add")
                if(!checkUsername1(out,loginDb, user_name, passwd, disp_name, typeUser , "add", bossOfNewUser)){
                    out.println("<div><b>Invalid Add action</b>: User name is exist!!!</div>");
                }else{
                    out.println("<div> User: <b>"+ user_name + "</b> was added in <b>"+ type_user + " </b>type</div>");
                    //todo add
                }
            }
        }else if(pressed_button.equals("remove")){
            if(user_name.equals("") || passwd.equals("") || !passwd.equals(re_passwd)){
                out.println("<div><b>Invalid Remove action</b>: User name,passwd must not blank, retype passwd must match with passwd!!!</div>"
                        );
            }
            else{
                //check and remove user
                if(!checkUsername1(out,loginDb, user_name, passwd, disp_name, typeUser, "remove", bossOfNewUser)){
                    out.println("<div><b>Invalid Remove action</b>: User name or password is invalid!!!</div>");
                }
                else{
                    out.println("<div> User: <b>"+ user_name + "</b> was removed</div>");
                    //todo remove
                }
            }
        }
        out.println("<div id=\"header-tip\"></div>"
                    +"<form name=\"HanderContentComment\">"
                    +"<br class=\"clear-all\">"
                    +"<br class=\"clear-all\">"
                    +"<table id=\"content-action-table\" cellpadding=\"0\" cellspacing=\"0\">"
                    +"<thead>"
                    +"<tr>"
                    +"<th class=\"table-the-first\">#</th>"
                        +"<th class=\"table-1\">User</th>"
                        +"<th class=\"table-2\">Display Name</th>"
                        +"<th class=\"table-3\">User type</th>"
                        +"<th class=\"table-5\">Last Login</th>"
                    +"</tr>"
                    +"</thead>"
                    +"<tbody id=\"table-body\">");
                        show_user_info2(out, currUserType, currUserName);
            out.println("</tbody>"
                    +"</table>"
                    +"<br class=\"clear-all\">"
                    +"<br class=\"clear-all\">"
                    +"</form>"
                    +"</div>"
                    +"</div>"
                    +"</div>"
                    );
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet add_remove_user</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet add_remove_user at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(add_remove_user.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(add_remove_user.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(add_remove_user.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(add_remove_user.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
